<script>
import { getEnterpriceIndustryList, postParkEnterpriseApi, editParkEnterpriseApi, getParkEnterpriceInfoApi } from '@/api/parkEnterprise'
import { uploadFileApi } from '@/api/common'
export default {
  name: 'AddEnterprice',
  data() {
    return {
      industryList: [],
      fileList: [], // 上传文件的列表
      optionList: [],
      updateEnterpriceData: {
        name: '', // 企业名称
        legalPerson: '', // 企业法人
        registeredAddress: '', // 注册地址
        industryCode: '', // 行业编号
        businessLicenseUrl: '', // 上传文件url
        businessLicenseId: '' // 上传文件id
      },
      updateRecentMonthCardPrice: {
        contact: '', // 企业联系人
        contactNumber: '' // 企业联系方式
      },
      // 下面的是表单验证规则
      enterpriceDataRole: {
        name: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        legalPerson: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        registeredAddress: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        industryCode: [
          { required: true, message: '必填项', trigger: 'change' }
        ],
        businessLicenseUrl: [
          { required: true, message: '必填项', trigger: 'change' }
        ],
        businessLicenseId: [
          { required: true, message: '必填项', trigger: 'change' }
        ]
      },
      recentMonthCardPriceRole: {
        contact: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        contactNumber: [
          { required: true, message: '必填项', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    mode() {
      return this.$route.query.mode
    },
    id() {
      return this.$route.query.id
    }
  },
  created() {
    this.getEnterpriceIndustryList()
    this.getEnterpriceIndustryInfo()
  },
  methods: {
    // 点击重置按钮，重置所有表单
    resetForm() {
      const enterpriceDataForm = this.$refs.enterpriceDataForm
      const recentMonthCardPriceForm = this.$refs.recentMonthCardPriceForm
      enterpriceDataForm.resetFields()
      recentMonthCardPriceForm.resetFields()
    },
    // 点击确认提交
    uploadConfirm() {
      // 开始校验
      const enterpriceDataForm = this.$refs.enterpriceDataForm
      const recentMonthCardPriceForm = this.$refs.recentMonthCardPriceForm
      enterpriceDataForm.validate((flag) => {
        if (!flag) return
        recentMonthCardPriceForm.validate(async(flag) => {
          if (!flag) return
          console.log('校验成功，准备上传数据')
          const updateData = Object.assign({}, this.updateEnterpriceData, this.updateRecentMonthCardPrice)
          if (this.id) {
            // id存在时为编辑企业
            updateData.id = this.id
            const res = await editParkEnterpriseApi(updateData)
            if (res.code === 10000) {
              this.$message({ type: 'success', message: '修改成功' })
              this.$router.back()
            } else {
              this.$message({ type: 'error', message: `${res.msg}` })
            }
          } else {
            // id不存在就为添加企业
            const res = await postParkEnterpriseApi(updateData)
            if (res.code === 10000) {
              this.$message({ type: 'success', message: '上传成功' })
              this.$router.back()
            } else {
              this.$message({ type: 'error', message: '上传错误，请联系管理员' })
            }
          }
        })
      })
    },
    async getEnterpriceIndustryList() {
      const res = await getEnterpriceIndustryList()
      if (res.code === 10000) {
        this.optionList = res.data
      }
    },
    // 上传文件前的钩子
    onBeforeUpload(file) {
      const fileType = ['image/jpeg', 'image/gif', 'image/png']
      if (file.size / 1024 > 500) {
        this.$message({ type: 'error', message: '上传文件大小不能大于500kb' })
        return Promise.reject()
      }
      if (!fileType.includes(file.type)) {
        this.$message({ type: 'error', message: '上传文件的类型错误' })
        return Promise.reject()
      }
    },
    // 上传的方法
    async uploadFileMethod({ file }) {
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', 'businessLicense')
      const res = await uploadFileApi(formData)
      // 将返回的链接给要上传的表单数据
      if (res.code === 10000) {
        this.updateEnterpriceData.businessLicenseUrl = res.data.url
        this.updateEnterpriceData.businessLicenseId = res.data.id
      }
    },
    // 移除文件时触发的钩子
    onRemoveFile() {
      this.updateEnterpriceData.businessLicenseUrl = ''
      this.updateEnterpriceData.businessLicenseId = ''
    },
    // 成功上传后需要清空校验信息
    onSuccessUpload() {
      const enterpriceDataForm = this.$refs.enterpriceDataForm
      enterpriceDataForm.clearValidate('businessLicenseUrl')
      enterpriceDataForm.clearValidate('businessLicenseId')
    },
    async getEnterpriceIndustryInfo() {
      // 有id时才获取数据
      if (!this.id) return
      const res = await getParkEnterpriceInfoApi(this.id)
      if (res.code === 10000) {
        // 回显数据
        for (const key in this.updateEnterpriceData) {
          if (Object.prototype.hasOwnProperty.call(this.updateEnterpriceData, key) && Object.prototype.hasOwnProperty.call(res.data, key)) {
            this.updateEnterpriceData[key] = res.data[key]
          }
        }
        this.updateRecentMonthCardPrice.contact = res.data.contact
        this.updateRecentMonthCardPrice.contactNumber = res.data.contactNumber
      }
    }
  }
}
</script>
<template>
  <div class="container">
    <div class="top">
      <div class="left">
        <i class="el-icon-back" @click="$router.back()" />
        <span class="back" @click="$router.back()">返回</span>
        <span class="divide">|</span>
        <div class="add">{{ mode==='edit'?'编辑企业':'添加企业' }}</div>
      </div>
      <div class="right">
        <div class="userInfo">
          管理员
        </div>
      </div>
    </div>
    <div class="center">
      <div class="inner-one">
        <div class="inner-header">
          <div class="border-left">
            <span class="text">企业信息</span>
          </div>
        </div>
        <div class="form-body">
          <div class="inner-form-in">
            <el-form ref="enterpriceDataForm" class="inner-form" label-width="30%" :model="updateEnterpriceData" :rules="enterpriceDataRole">
              <el-form-item prop="name" label="企业名称:" style="width: 50%;">
                <el-input v-model="updateEnterpriceData.name" style="width: 95%;" class="input" size="medium" placeholder="请输入企业名称" />
              </el-form-item>
              <el-form-item prop="legalPerson" label="法人:" style="width: 50%;">
                <el-input v-model="updateEnterpriceData.legalPerson" style="width: 95%;" class="input" size="medium" placeholder="请输入法人" />
              </el-form-item>
              <el-form-item prop="registeredAddress" label="注册地址:" style="width: 50%;">
                <el-input v-model="updateEnterpriceData.registeredAddress" style="width: 95%;" class="input" size="medium" placeholder="请输入注册地址" />
              </el-form-item>
              <el-form-item prop="industryCode" label="所在行业:" style="width: 50%;">
                <el-select v-model="updateEnterpriceData.industryCode" placeholder="请选择所在行业">
                  <el-option v-for="item in optionList" :key="item.industryCode" :label="item.industryName" :value="item.industryCode" />
                </el-select>
              </el-form-item>
              <el-form-item label="营业执照:" style="width: 50%;" prop="businessLicenseUrl">
                <el-upload
                  class="upload-demo"
                  action="#"
                  :limit="1"
                  :file-list="fileList"
                  :before-upload="onBeforeUpload"
                  :http-request="uploadFileMethod"
                  :on-remove="onRemoveFile"
                  :on-success="onSuccessUpload"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">支持扩展名：.png .jpg .jpeg，文件大小不得超过5M</div>
                </el-upload>
                <img :src="updateEnterpriceData.businessLicenseUrl" style="width: 20%;display: block">
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <div class="inner-one box2 ">
        <div class="inner-header">
          <div class="border-left">
            <span class="text">最近一次月卡缴费信息</span>
          </div>
        </div>
        <div class="form-body">
          <div class="inner-form-in">
            <el-form ref="recentMonthCardPriceForm" class="inner-form" label-width="30%" :model="updateRecentMonthCardPrice" :rules="recentMonthCardPriceRole">
              <el-form-item prop="contact" label="企业联系人:" style="width: 50%;">
                <el-input v-model="updateRecentMonthCardPrice.contact" style="width: 95%;" class="input" size="medium" placeholder="请输入企业联系人" />
              </el-form-item>
              <el-form-item prop="contactNumber" label="联系电话:" style="width: 50%;">
                <el-input v-model="updateRecentMonthCardPrice.contactNumber" style="width: 95%;" class="input" size="medium" placeholder="请输入联系电话" />
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
    <div class="bottom">
      <div class="center">
        <el-button size="small" @click="resetForm">重置</el-button>
        <el-button type="primary" size="small" @click="uploadConfirm">确定</el-button>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.container {
  background-color: #f4f6f8;
  width:100%;
  height: 100%;
  font-size: 16px;
  .top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 64px;
    background-color: #fff;
    .left {
      display: flex;
      align-items: center;
      margin-left: 20px;
      .el-icon-back {
        font-size: 19px;
        margin-right: 5px;
      }
      .back {
        cursor: pointer;
      }
      .divide {
        margin: auto 10px;
      }
    }
    .right {
      margin-right: 2%;
      .text {
        font-size: 16px
      }
    }
  }
  .center{
    height: 100%;
    .inner-one {
        width: 85%;
        margin: 24px auto;
        background-color: #fff;
        min-height: 30%;
        .inner-header{
            display: flex;
            align-items: center;
          // background-color: palevioletred;
          width: 100%;
          height: 58px;
          .border-left {
            border-left: 2px solid #4770ff;
            height: 18px;
            .text {
            margin-left: 24px;
          }
          }

        }
        .form-body{
          display: flex;
          padding: 24px;
          justify-content: center;
          .inner-form-in {
            // background-color: yellow;
            width:100%;
            .inner-form {
              display: flex;
              flex-wrap: wrap;
              ::v-deep .el-form-item__label {
                font-weight: 400;
                color: #000000d9;
              }
              .upload-demo {
                width: 80%;
              }
            }
          }
        }
    }
    & .box2  {
        height: 200px;
    }
  }
  .bottom {
    background-color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    bottom: 0;
    height: 80px;
    width: 100%;
    .center {
      transform: translateY(10%);
      height: 50%;
      width: 10%;
    }
  }
}
</style>
<style lang="scss" >
.carcard-pagination-select {
   .el-select-dropdown__item.selected {
    color: #000000D9;
  }
}
</style>
